/*
 * @Author: your name
 * @Date: 2021-03-15 09:17:40
 * @LastEditTime: 2021-11-19 11:21:16
 * @LastEditors: your name
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vue-blog-web\src\plugins\GlobalErrorPlugin.js
 */
import { isPromise } from '@utils/CommonUtil'

// 同步异常处理
const errorHandler = (err, vm, info) => {
  console.log('进去全局异常11')
  console.log('err: ', err)
  console.log('vm: ', vm)
  console.log('info: ', info)
  vm.$message({
    type: 'error',
    message: 'vue出错' + info
  })
}

// 异步异常处理
const errorPHandler = (err, vm) => {
  vm.$message({
    type: 'error',
    message: err
  })
}

// 获取vue实例中是Promise方法,将该方法异常抛给errorHandler处理
const registerVue = instance => {
  const methods = instance.$options.methods
  console.log('registerVue', methods)
  if (!methods) return
  Object.keys(methods).forEach(key => {
    console.log('registerVue key', key)
    const fn = methods[key]
      methods[key] = function (...args) {
        const ret = fn.apply(this, args)
        if (isPromise(ret)) {
          console.log('registerVue isPromise 0', typeof ret)
          return ret.catch((err) => errorPHandler(err, this))
        } else {
          console.log('registerVue isPromise 1', ret)
          return ret
        }
      }
  })
}

// 全局错误处理插件 https://cn.vuejs.org/v2/guide/plugins.html
const GlobalErrorPlugin = {
  install: Vue => {
    // 同步代码,全局异常处理
    Vue.config.errorHandler = errorHandler
    // 异步代码(promise),全局异常处理
    Vue.mixin({
      beforeCreate() {
        registerVue(this)
      }
    })
  }
}

export default GlobalErrorPlugin